<?php
class OAuthAction extends CommonAction {
	/**
	 * 获取微博登陆连接地址
	 * @author ice <iceinto@mallog.com.cn>
	 */
	public function getWeiBoLoginUrl($url){
		vendor('WeiBo.WeiBo');
		$o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );
		$code_url = $o->getAuthorizeURL($url);
		return $code_url;
	}
	/**
	 * 微博登陆返回信息
	 * @author ice <iceinto@mallog.com.cn>
	 */
	public function weibo(){
		vendor('WeiBo.WeiBo');
		$token = null;
		$o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );
		if (isset($_REQUEST['code'])) {
			$keys = array();
			$keys['code'] = $_GET['code'];
			$keys['redirect_uri'] = SITE_URL.U('OAuth/weibo');
			try {
				$token = $o->getAccessToken('code', $keys);
			} catch (OAuthException $e) {
				dump($e->getMessage());
			}
		}

		if($token != null){
			$oauth = $this->checkOAuth('weibo', $token['access_token']);
			$this->assign('jumpUrl', U('Member/oauth'));
			if($oauth){
				$this->successLang('_UPDATE_SUCCESS');
			}else{
				$this->errorLang('_UPDATE_LOSE');
			}
		}else{
			$this->error('TOKEN 获取错误！');
		}
		$this->showBrowMes();
	}

	/**
	 * 查看OAuth
	 * @param string $site
	 * @param string $openid
	 * @author ice <iceinto@mallog.com.cn>
	 */
	public function checkOAuth($site, $openid){
		$OAuthModel = D('OAuth');
		//1.获取 oauth 表中是否用户已经绑定
		//2.如果没有绑定 则进行绑定 或者 注册
		//3.如果已经绑定则进行登陆操作
		$uid = $this->getLoginUserInfo();
		$oauth = $OAuthModel->getOne($site, $openid);
		if($oauth){
			//添加一次登陆信息
			$data = array();
			$data['itemid'] = $oauth['itemid'];
			$data['login_count'] = array('exp', 'login_count+1');
			$data['login_time'] = time();
			$data['uid'] = $uid;
			return $OAuthModel->save($data);
		}else{
			//添加 oauth
			$data = array();
			$data['add_time'] = time();
			$data['site'] = $site;
			$data['openid'] = $openid;
			$data['uid'] = $uid;
			return $OAuthModel->add($data);
		}
	}

	/**
	 * 解除绑定
	 */
	public function unbind(){
		$uid = $this->getLoginUserInfo();
		if($uid){
			$type = getGet('type');
			$OAuthModel = D('OAuth');
			$oauth = $OAuthModel->getUserOneBind($uid, $type);
			if($oauth){
				$data['uid'] = 0;
				$data['itemid'] = $oauth['itemid'];
				$rs = $OAuthModel->save($data);
				if($rs){
					$this->assign("jumpUrl", U('Member/oauth'));
					$this->success('解绑成功！');
				}else{
					$this->error('解绑失败！');
				}
			}else{
				$this->error('绑定信息不存在！');
			}
		}
	}
}
?>